#include "family.h"
#include <algorithm> // 包含 std::find
#include <map>       // 包含 std::map

void FamilyTree::deleteMember(FamilyMember *member)
{
    if (member == nullptr)
    {
        std::cerr << "成员不存在，无法删除。" << std::endl;
        return;
    }

    // 如果删除的是根节点
    if (member == root)
    {
        root = nullptr;
        for (auto child : member->children)
        {
            delete child; // 递归删除所有子节点
        }
        delete member;                 // 删除根节点
        memberMap.erase(member->name); // 从 memberMap 中移除该成员
        return;
    }

    // 查找父节点
    for (auto it = memberMap.begin(); it != memberMap.end(); ++it)
    {
        FamilyMember *parent = it->second;
        auto childIt = std::find(parent->children.begin(), parent->children.end(), member);
        if (childIt != parent->children.end())
        {
            // 从父节点的children列表中移除该成员
            parent->children.erase(childIt);
            for (auto child : member->children)
            {
                delete child; // 递归删除所有子节点
            }
            delete member;                 // 删除该成员
            memberMap.erase(member->name); // 从 memberMap 中移除该成员
            return;
        }
    }

    std::cerr << "未找到成员的父节点，无法删除。" << std::endl;
}